﻿using System;
using System.IO;
using System.Windows.Forms;
using Weather.common;
using Newtonsoft.Json;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;
using System.Security.Policy;
using static System.Net.WebRequestMethods;
using System.Xml.Linq;
using File = System.IO.File;
using Newtonsoft.Json.Linq;
using System.Diagnostics;
using Weather.Forms;
using System.Drawing;
using System.Numerics;


namespace Weather
{

    public partial class weatrherMainForm : Form
    {
        private ProvincesData provincesData; // 总数据
        private Province province;      //省
        private City city;      //市
        private Area area;  //地区
        WeatherInfo yesterday;


        public weatrherMainForm()
        {
            InitializeComponent();
        }


        private void weatrherMainForm_Load(object sender, EventArgs e)
        {
            // 读取 area.json 文件并初始化类的实例
            string jsonFilePath = Path.Combine(Directory.GetParent(Environment.CurrentDirectory).Parent.FullName, @"common\area.json");

            #region 将城市总数据绑定在当前窗口上
            try
            {
                // 检查文件是否存在
                if (File.Exists(jsonFilePath))
                {
                    // 读取 JSON 文件内容
                    string jsonData = File.ReadAllText(jsonFilePath);

                    // 反序列化 JSON 数据
                    provincesData = JsonConvert.DeserializeObject<ProvincesData>(jsonData);

                    // 绑定省份数据
                    this.Province_comboBox.DataSource = provincesData.Provinces.Keys.ToList();
                }
                else
                {
                    MessageBox.Show("本地缺少了地区配置文件，请前往下载，下载后请添加至项目的common中");
                    // 文件不存在，执行跳转到下载链接的操作（示例中为打开浏览器）
                    Process.Start("https://kangkan.oss-cn-beijing.aliyuncs.com/area.json");
                    this.Close();
                }
            }
            catch (FileNotFoundException ex)
            {
                Console.WriteLine($"JSON 文件未找到: {ex.Message}");
            }
            catch (IOException ex)
            {
                Console.WriteLine($"IO 错误发生: {ex.Message}");
            }
            catch (JsonException ex)
            {
                Console.WriteLine($"JSON 解析错误: {ex.Message}");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"初始化数据发生错误: {ex.Message}");
            }
            #endregion
        }


        // 省份数据改变后的行为
        private void Province_comboBox_SelectedIndexChanged(object sender, EventArgs e)
        {
            #region 当用户选择了省份的数据后，将城市信息绑定到城市选择器中
            try
            {
                //获取省份框内的值
                string provinceName = (string)this.Province_comboBox.SelectedValue;

                province = provincesData.Provinces[provinceName];

                if (province != null)
                {
                    // 绑定省份数据
                    this.City_comboBox.DataSource = province.Citys.Keys.ToList();
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"省份选择 Error: {ex.Message}");
                province = null;
            }
            #endregion

        }

        private void City_comboBox_SelectedIndexChanged(object sender, EventArgs e)
        {
            #region 当用户选择了城市的数据后，将地区信息绑定到地区选择器中
            try
            {
                string cityName = (string)this.City_comboBox.SelectedValue;
                city = province.Citys[cityName];

                if (city != null)
                {
                    // 绑定省份数据
                    this.Area_comboBox.DataSource = city.Areas.Select(area => area.AreaName).ToList();
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"城市选择 Error: {ex.Message}");
                city = null;
            }
            #endregion
        }

        private void Area_comboBox_SelectedIndexChanged(object sender, EventArgs e)
        {
            #region 当用户选择了地区的数据后，输出信息
            try
            {
                string areaName = (string)this.Area_comboBox.SelectedValue;

                area = city.Areas.FirstOrDefault(area => area.AreaName == areaName);

                if (city != null)
                {
                    Console.WriteLine(area.AreaName, area.CityCode);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"地区选择 Error: {ex.Message}");
                city = null;
            }
            #endregion
        }

        // 点击查询即可查询天气(要调用一个异步方法）
        private async void search_Button_ClickAsync(object sender, EventArgs e)
        {
            string resultJsonString = await Task.Run(() => search_weatherData(area.CityCode));


            if (resultJsonString != null)
            {
                // 解析 JSON 字符串
                JObject resultJsonObject = JObject.Parse(resultJsonString);

                CityInfo cityInfo = resultJsonObject["cityInfo"].ToObject<CityInfo>();

                WeatherDatas weatherDatas = resultJsonObject["data"].ToObject<WeatherDatas>();

                yesterday = resultJsonObject["data"]["yesterday"].ToObject<WeatherInfo>();

                weatherDatas.Weathers.Insert(0,yesterday);

                this.parent_label.Text = cityInfo.Parent;
                this.city_label.Text = cityInfo.City;
                this.updateTime_label.Text = $"更新时间：{cityInfo.UpdateTime}";

                this.Humidity_Label.Text = weatherDatas.Humidity;
                this.PM25_Label.Text = $"{weatherDatas.PM25}";
                this.AirQuality_Label.Text = $"{weatherDatas.AirQuality}";
                this.Tips_Label.Text = $"{weatherDatas.HealthTip}";
                this.Temperature_Label.Text = $"{weatherDatas.Temperature}℃";
                this.uiThermometer.Value = (int)Math.Round(double.Parse(weatherDatas.Temperature));


                foreach (WeatherInfo weatherInfo in weatherDatas.Weathers)
                {
                    FEasyWeather fEasyWeather = new FEasyWeather(weatherInfo);
                    fEasyWeather.TopLevel = false;

                    // 创建一个 Panel 控件来容纳 fEasyWeather
                    Panel panel = new Panel();
                    panel.AutoSize = true; // 自动调整大小以适应内容

                    // 将 fEasyWeather 添加到 Panel 中
                    panel.Controls.Add(fEasyWeather);

                    // 将 Panel 添加到 FlowLayoutPanel 中
                    Weather_FlowLayoutPanel.Controls.Add(panel);

                    // 显示 fEasyWeather
                    fEasyWeather.Show();
                }


            }

        }

        // async 是用来定义异步方法的关键字
        private async Task<string> search_weatherData(string cityCode)
        {
            // 请求地址
            string url = $"http://t.weather.sojson.com/api/weather/city/{cityCode}";

            #region 创建一个 HttpClient 实例
            using (HttpClient client = new HttpClient())
            {
                try
                {
                    // 发送 GET 请求并获取响应
                    HttpResponseMessage response = await client.GetAsync(url);

                    // 确保请求成功
                    response.EnsureSuccessStatusCode();

                    // 读取响应内容并输出
                    string responseBody = await response.Content.ReadAsStringAsync();

                    return responseBody;
                }
                catch (HttpRequestException ex)
                {
                    MessageBox.Show($"查询请求发生错误: {ex.Message}");
                    return null;
                }
            }
            #endregion
            
        }


        private void Weather_FlowLayoutPanel_Paint(object sender, PaintEventArgs e)
        {
           
        }
    }
}
